package com.xxf.aynu.parking;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.OverlayManager;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;

import java.util.ArrayList;
import java.util.List;

public class activity_showmap extends AppCompatActivity {
    private LocationClient locationClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    boolean isFirstLoc = true;
    /** 百度地图 */
    private MapView mapView;
    /** 定义 BaiduMap 地图对象的操作方法与接口 */
    private BaiduMap baiduMap;
    private PoiSearch poiSearch;
    /** 搜索关键词 */
    private  String keyword = "停车场";
    private  String mycity="郑州";
    /** 每页容量50 */
    private final int pageCapacity = 20;
    /** 第一页 */
    private final int pageNum = 0;
    /** 搜索半径10km */
    private final int radius = 10000;

    RadioGroup group;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        //获取百度地图控件
        mapView = (MapView) findViewById(R.id.bm);
        //获取百度地图对象
        baiduMap = mapView.getMap();
        // 开启定位图层
        baiduMap.setMyLocationEnabled(true);
        initView();

        //Poi检索相关
        // 搜索该坐标附近的餐厅
        poiSearch = PoiSearch.newInstance();
        poiSearch.setOnGetPoiSearchResultListener(new OnGetPoiSearchResultListener() {
            @Override
            public void onGetPoiResult(PoiResult poiResult) {
                if ((poiResult == null) || (poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND)) {
                    Toast.makeText(getApplicationContext(),"无结果", Toast
                            .LENGTH_SHORT).show();
                    return;
                }
                if (poiResult.error== SearchResult.ERRORNO.NO_ERROR) {
                    baiduMap.clear();
                    MyPoiOverlay overlay = new MyPoiOverlay(baiduMap);
                    baiduMap.setOnMarkerClickListener(overlay);
                    overlay.setData(poiResult);
                    overlay.addToMap();
                    // 缩放地图，使所有Overlay都在合适的视野内
                    overlay.zoomToSpan();
                    return;
                }
                if (poiResult.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {
                }

            }

            @Override
            public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
                if (poiDetailResult.error != SearchResult.ERRORNO.NO_ERROR) {
                } else
                {

                    Toast.makeText(getApplicationContext(), poiDetailResult.getName() + ": " + poiDetailResult.getAddress(), Toast
                            .LENGTH_SHORT).show();
                }

            }

            @Override
            public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

            }
        });
        poiSearch.searchInCity(new PoiCitySearchOption().city(mycity).keyword(keyword)
                .pageCapacity(pageCapacity).pageNum(pageNum));
        /**
         * poiSearch.searchNearby(new PoiNearbySearchOption().keyword(keyword)
         .location(new LatLng(39.904965, 116.327764))
         .pageCapacity(pageCapacity).pageNum(pageNum).radius(radius));
         * */



            // initView();
        // initData();
        group=(RadioGroup)findViewById(R.id.tab_radioGroup);
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch(checkedId)
                {

                    case R.id.rb_world:
                        Intent intent=new Intent();
                        intent.setClass(getApplicationContext(), activity_youhui.class);
                        startActivity(intent);

                        break;
                    case R.id.rb_home:
                        Intent intent1=new Intent();
                        intent1.setClass(getApplicationContext(), activity_park.class);
                        startActivity(intent1);
                        break;
                    case R.id.rb_mine:
                        Intent intent2=new Intent();
                        intent2.setClass(getApplicationContext(), activity_mine_unlog.class);
                        //item.setIntent(intent);
                        startActivity(intent2);
                        activity_showmap.this.finish();
                        break;
                }

            }
        });

    }
    //定位相关
    private void initView() {
        baiduMap.setMyLocationEnabled(true);
        locationClient = new LocationClient(this);
        //注册监听
        locationClient.registerLocationListener(myListener);
        //定位配置信息
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);//定位请求时间间隔
        locationClient.setLocOption(option);
        //开启定位
        locationClient.start();
    }

    @Override
    protected void onPause() {
        mapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        // 销毁搜索模块
        poiSearch.destroy();
        // 关闭定位图层
        baiduMap.setMyLocationEnabled(false);
        mapView.onDestroy();
        mapView = null;
        super.onDestroy();

    }


    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location)
        {
            if(location==null||mapView==null)
            {return;}
            MyLocationData locaData = new MyLocationData.Builder().accuracy(location.getRadius())
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            baiduMap.setMyLocationData(locaData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

            }

        }
        public  void onReceivePoi(BDLocation poiLocation){

        }
        public void onConnectHotSpotMessage(String s, int i){

        }
    }


    private class MyPoiOverlay extends OverlayManager{
        private PoiResult poiResult;

        public MyPoiOverlay(BaiduMap baiduMap){
            super(baiduMap);
        }
        @Override
        public boolean onMarkerClick(Marker marker){
            if (marker.getExtraInfo() != null) {
                int index = marker.getExtraInfo().getInt("index");
                PoiInfo poi = poiResult.getAllPoi().get(index);
                // 详情搜索
                poiSearch.searchPoiDetail((new PoiDetailSearchOption())
                        .poiUid(poi.uid));
                return true;
            }
            return false;
        }
        @Override
        public boolean onPolylineClick(Polyline polyline)
        {
            return true;
        }
        @Override
        public List<OverlayOptions>getOverlayOptions(){
            if ((this.poiResult == null)
                    || (this.poiResult.getAllPoi() == null))
                return null;
            ArrayList<OverlayOptions> arrayList = new ArrayList<OverlayOptions>();
            for (int i = 1; i < this.poiResult.getAllPoi().size(); i++) {
                if (this.poiResult.getAllPoi().get(i).location == null)
                    continue;
                // 给marker加上标签
                Bundle bundle = new Bundle();
                bundle.putInt("index", i);
                arrayList.add(new MarkerOptions()
                        .icon(BitmapDescriptorFactory
                                .fromBitmap(setNumToIcon(i)))
                        .extraInfo(bundle)
                        .position(this.poiResult.getAllPoi().get(i).location) );

            }
            return arrayList;
        }



        /**
         * 往图片添加数字
         */
        private Bitmap setNumToIcon(int num) {
            BitmapDrawable bd = (BitmapDrawable)getDrawable(
                    R.drawable.icon_gcoding);
            Bitmap bitmap = bd.getBitmap().copy(Bitmap.Config.ARGB_8888, true);
            Canvas canvas = new Canvas(bitmap);

            Paint paint = new Paint();
            paint.setColor(Color.WHITE);
            paint.setAntiAlias(true);
            int widthX;
            int heightY = 0;
            if (num < 10) {
                paint.setTextSize(30);
                widthX = 8;
                heightY = 6;
            } else {
                paint.setTextSize(20);
                widthX = 11;
            }

            canvas.drawText(String.valueOf(num),
                    ((bitmap.getWidth() / 2) - widthX),
                    ((bitmap.getHeight() / 2) + heightY), paint);
            return bitmap;
        }

        public void setData(PoiResult poiResult) {
            this.poiResult = poiResult;
        }

    }
  /*  private void citySearch(int page) {
        // 设置检索参数
        PoiCitySearchOption citySearchOption = new PoiCitySearchOption();
        citySearchOption.city(mycity);// 城市
        citySearchOption.keyword(keyword);// 关键字
        citySearchOption.pageCapacity(15);// 默认每页10条
        citySearchOption.pageNum(page);// 分页编号
        // 发起检索请求
        poiSearch.searchInCity(citySearchOption);
    }*/





}
